<template>
  <div class="flashBZU front-color">
    <div class="operate">
      <p class="available"><span>{{$t('myAdd.income.available')}}</span> <span>{{exchangeInterfaceInfo.balance}} {{formList.payCoin.value}}</span><span> = </span><span>{{availableGetSymbol}} {{exchangeInterfaceInfo.getSymbol}}</span><span class="rate">{{$t('myAdd.income.rate')}}: {{exchangeInterfaceInfo.rate}}</span></p>
      <div class="operateInput clearfix">
        <div class="select">
          <inline-input
            v-bind:property = "formList.payCoin"
            v-model = "formList.payCoin.value"
            v-on:onevents = "somethings">
          </inline-input>
          <span class="coinImg"><img :src="showIconImg || coinImg" alt="."></span>
        </div>
        <div class="enter">
          <inline-input
            v-bind:property = "formList.payCoinNum"
            v-model = "formList.payCoinNum.value"
            v-on:onevents = "somethings">
          </inline-input>
        </div>
        <span class="all pointer" @click="allEnter">{{$t('myAdd.income.all')}}</span>
      </div>
      <p class="error" v-show="errorInfo">{{errorInfo}}</p>
      <div class="limit">
        <p class="getted">{{$t('myAdd.income.getCoinIs', {coin: exchangeInterfaceInfo.getSymbol})}} <span class="getted_num">{{myData.getQuantity || '--'}} <span v-if="!zoologyUserInfoData.giveQuantity">{{giveQuantity}}</span></span></p>
        <p class="flash_limit"><span>{{exchangeInterfaceInfo.minQuantity}} {{exchangeInterfaceInfo.getSymbol}}</span> <= <span>{{$t('myAdd.income.availableAmount')}}</span> <= <span>{{exchangeInterfaceInfo.maxQuantity}} {{exchangeInterfaceInfo.getSymbol}}</span></p>
      </div>
      <div class="welfare" v-if="!zoologyUserInfoData.giveQuantity && exchangeInterfaceInfoComboMapLeng">
        <div class="welfare_title">
          <span>{{$t('myAdd.income.firstPurchase')}}</span>
          <span class="user_remain fontsize14">( {{$t('myAdd.income.giftBenefits')}} )</span>
        </div>
        <div class="welfare_choose clearfix">
          <div class="welfare_item pointer" v-for="(item, index) in exchangeInterfaceInfo.comboMap" :key="index" @click="chooseWelfare(item)" :class="{selected: item.isChoose}">
            <p class="own">{{item && item.getQuantity}} {{exchangeInterfaceInfo.getSymbol}}</p>
            <p class="sent">{{$t('myAdd.income.give')}} {{item && item.giveQuantity}} {{exchangeInterfaceInfo.getSymbol}}</p>
            <span class="triangle"><span class="check_mark"></span></span>
          </div>
        </div>
      </div>
      <!-- 锁仓分红套餐 -->
      <div class="lockingPackage" v-if="exchangeInterfaceInfolockMapListLeng">
        <div class="welfare_title">
          <span>{{$t('myAdd.income.lockedTitle')}}</span>
        </div>
        <div id="lockedPackage" class="welfare_choose clearfix" ref="lockedPackage">
          <div class="locked_item pointer" v-for="(item, index) in exchangeInterfaceInfo.lockMapList" :key="index" :class="{lockedSelected: index === 0}" :ref="'lockedPackage' + index" @click="chooseLockedPackage(item, index)">
            <p class="fee fontWeight500">
              <span class="feeVal">{{_P.accMul(item.fee, 100)}}</span><span class="percent fontsize14">%</span>
            </p>
            <p class='text'>{{$t('myAdd.income.gift')}}</p>
            <p class="period fontsize16">{{$t('myAdd.income.lockedDays', {period: item.period})}}</p>
          </div>
        </div>
        <div class="release fontsize16">
          <span class="time">{{$t('myAdd.income.timeAndQuality', {period: showLockedPackagedInfo.period, quantity: _P.accDiv(showLockedPackagedInfo.quantity, 10000)})}}</span><span class="tell_user">{{$t('myAdd.income.tellUser', {time: showLockedPackagedInfo.time})}}</span>
        </div>
      </div>
      <div class="btn"><button :class="{readOnly: !isCanFlash}" @click="fastFlash">{{$t('myAdd.income.fastFlash')}}</button></div>
    </div>
    <exchangePw :passWordAlert = "passWordAlert" @closePassWordAlert="closePassWordAlert" @submitRequest="submitRequest"></exchangePw>
    <!-- 设置交易密码弹窗 -->
    <elDialog
      title= ''
      :flag= 'setExPw'
      name= 'setExPw'
      :width= '450'
      :dialogClose= 'closeDialog'>
      <div class="realNameCont" slot="content">
        {{$t('myAdd.income.setExP')}}
      </div>
      <div slot="options">
        <button @click="closeDialog" class="cancel">{{$t('myAdd.income.cancel')}}</button>
        <router-link tag="button" :to="{path: 'personal/setExPassW'}">{{$t('myAdd.income.toSet')}}</router-link>
      </div>
    </elDialog>
    <!-- 兑换成功 -->
    <elDialog
      title= ''
      :flag= 'detailAlert'
      name= 'detailAlert'
      :width='450'
      :dialogClose='closeDialog'>
      <div class="detailTitle" slot="operation">
        {{$t('myAdd.income.flashDetail')}}
      </div>
      <div class="detailAlertData" slot="content">
        <div class="side"><span>{{detailAlertData.paySymbol}}</span><i class="icon-uniE958"></i><span>{{detailAlertData.getSymbol}}</span></div>
        <div class="data">
          <p><span class="text">{{$t('myAdd.income.payAmount')}}</span><span class="num">{{detailAlertData.payQuantity}} {{detailAlertData.paySymbol}}</span></p>
          <p><span class="text">{{$t('myAdd.income.getQuantity')}}</span><span class="num">{{detailAlertData.getQuantity}} {{detailAlertData.getSymbol}}</span></p>
          <p><span class="text">{{$t('myAdd.income.rate')}}</span><span class="num">{{detailAlertData.rate}}</span></p>
          <p><span class="text">{{$t('myAdd.income.exchangeNumber')}}</span><span class="num">{{detailAlertData.exchangeNumber}}</span></p>
          <!-- 关于锁仓得信息暂时不展示  -->
        <!--  <p v-if="detailAlertData.lockFee"><span class="text">{{$t('myAdd.income.lockedFee')}}</span><span class="num">{{detailAlertData.lockFee}}</span></p>
          <p v-if="detailAlertData.period"><span class="text">{{$t('myAdd.income.lockedPeriod')}}</span><span class="num">{{detailAlertData.period}}</span></p>
          <p v-if="detailAlertData.lockEarnings"><span class="text">{{$t('myAdd.income.lockedcEarings')}}</span><span class="num">{{detailAlertData.lockEarnings}}</span></p>-->
          <p><span class="text">{{$t('myAdd.income.time')}}</span><span class="num">{{detailAlertData.ctime}}</span></p>
        </div>
      </div>
      <div class="detailAlertFooter" slot="options">
        <button @click="closeDialog" class="cancel">{{$t('myAdd.income.close')}}</button>
      </div>
    </elDialog>
    <b v-if="baseData"></b>
  </div>
</template>

<script>
import InlineInput from '@/components/common/inlineInput'
import coinImg from '@/assets/img/coindef.png'
import { mapState } from 'vuex'
import exchangePw from '@/components/common/addCommon/exchangePw'
import elDialog from '@/components/common/addCommon/dialog'

export default {
  name: 'flashBZU',
  components: { InlineInput, exchangePw, elDialog },
  props: {
    'zoologyUserInfoData': {
      type: Object
    },
    'getZoologySymbol': {
      type: String
    }
  },
  data () {
    return {
      formList: {},
      coinList: null,
      coinImg: coinImg,
      exchangeInterfaceInfo: {
        minQuantity: 0,
        maxQuantity: 0,
        balance: 0,
        rate: 0,
        getSymbol: '',
        paySymbol: '',
        comboMap: [],
        id: '',
        lockMapList: []
      },
      errorInfo: null,
      isCanFlash: true,
      myData: {
        paySymbol: '',
        payQuantity: '',
        getSymbol: '',
        getQuantity: '',
        rate: '',
        period: null,
        lockFee: null,
        time: null,
        quantity: '',
        lockEarnings: null,
        id: ''
      },
      secondClick: true,
      giveQuantity: '', // 显示的赠送 币 数量
      passWordAlert: false,
      ifSetExchangePwd: 0, // 是否设置了交易密码
      setExPw: false,
      detailAlert: false, // 交易记录详情弹窗
      detailAlertData: { // 弹窗详情的信息
        paySymbol: null,
        payQuantity: null,
        getSymbol: null,
        getQuantity: null,
        exchangeNumber: null,
        ctime: null,
        rate: null,
        lockFee: null,
        period: null,
        lockEarnings: null
      }
    }
  },
  created () {
    this.formList = this.formList_obj
    this.formList.payCoin.value = this.formListOption[0].code
  },
  mounted () {
    this.exchangeInterface()
  },
  computed: {
    ...mapState({
      baseData ({baseData}) {
        if (baseData.isReady) {
          this.coinList = baseData._coinList
          this.ifSetExchangePwd = baseData._user.ifSetExchangePwd
          return baseData
        } else {
          return false
        }
      }
    }),
    formList_obj () {
      return {
        payCoin: {
          title: '',
          placeholder: '',
          formType: 'select',
          name: 'payCoin',
          value: '',
          optionList: this.formListOption
        },
        payCoinNum: {
          title: '',
          placeholder: '',
          formType: 'number',
          name: 'payCoinNum',
          value: ''
        }
      }
    },
    showIconImg () {
      if (this.coinList && this.formList.payCoin.value) {
        return this.coinList[this.formList.payCoin.value].icon
      }
    },
    availableGetSymbol () {
      if (this.exchangeInterfaceInfo.getSymbol) {
        let result = this.exchangeInterfaceInfo.balance * this.exchangeInterfaceInfo.rate
        if (this.coinList && this.exchangeInterfaceInfo.getSymbol) {
          result = this._P.fixD(result, this.coinList[this.exchangeInterfaceInfo.getSymbol].showPrecision)
          result = this._P.lastD(result)
        }
        return result
      } else {
        return '0'
      }
    },
    Internationalization () {
      return {
        pay: this.$t('myAdd.income.pay'), // 支付
        overAvailableBalance: this.$t('myAdd.income.overAvailableBalance'), // 超出可用余额
        lessThanMiniLimit: this.$t('myAdd.income.lessThanMiniLimit'), // 小于兑换最小限额
        moreThanMaxLimit: this.$t('myAdd.income.moreThanMaxLimit'), // 大于兑换最大限额
        pleaseCheck: this.$t('myAdd.income.pleaseCheck'), // 请检查
        flashSuc: this.$t('myAdd.income.flashSuc'), // 兑换成功
        rateErr: this.$t('myAdd.income.rateErr') // 當前匯率異常,請聯繫管理員
      }
    },
    formListOption () {
      if (this.zoologyUserInfoData.paySymbolList.length > 0) {
        let arr = []
        this.zoologyUserInfoData.paySymbolList.forEach(item => {
          let obj = { value: item + ' ' + this.Internationalization.pay, code: item }
          arr.push(obj)
        })
        return arr
      }
    },
    exchangeInterfaceInfoComboMapLeng () {
      return this.exchangeInterfaceInfo.comboMap.length
    },
    exchangeInterfaceInfolockMapListLeng () {
      return this.exchangeInterfaceInfo.lockMapList.length
    },
    showLockedPackagedInfo () {
      let obj = {
        time: '',
        period: '',
        quantity: '',
        lockFee: ''
      }
      if (!this.myData.period && !this.myData.lockFee && !this.myData.time && !this.myData.quantity && this.exchangeInterfaceInfo.lockMapList.length) {
        obj.time = this.myData.time = this.exchangeInterfaceInfo.lockMapList[0].time
        obj.quantity = this.myData.quantity = this.exchangeInterfaceInfo.lockMapList[0].quantity
        obj.lockFee = this.myData.lockFee = this.exchangeInterfaceInfo.lockMapList[0].fee
        obj.period = this.myData.period = this.exchangeInterfaceInfo.lockMapList[0].period
      } else {
        obj.time = this.myData.time
        obj.quantity = this.myData.quantity
        obj.lockFee = this.myData.lockFee
        obj.period = this.myData.period
      }
      return obj
    }
  },
  watch: {
    'formList_obj' (val) {
      this.formList = val
      this.formList.payCoin.value = this.formListOption[0].code
    },
    'formList.payCoin.value' (newV) {
      if (newV) {
        this.exchangeInterface()
        this.formList.payCoinNum.value = ''
        this.myData.getQuantity = ''
        this.giveQuantity = ''
      }
    },
    coinList (newV) {
      if (newV && this.exchangeInterfaceInfo.balance) {
        this.exchangeInterfaceInfo.balance = this._P.fixD(this.exchangeInterfaceInfo.balance, newV[this.formList.payCoin.value].showPrecision)
        this.exchangeInterfaceInfo.balance = this._P.lastD(this.exchangeInterfaceInfo.balance)
      }
    }
  },
  methods: {
    somethings (data) {
      this.isCanFlash = true
      this.errorInfo = ''
      if (data.name === 'payCoinNum' && this.exchangeInterfaceInfo.paySymbol) {
        // val 不能大于余额； value 不能 小于 对小限额； value 不能大于 最大限额
        let paySshowPrecision = this.coinList[this.exchangeInterfaceInfo.paySymbol].showPrecision
        let getSshowPrecision = this.coinList[this.exchangeInterfaceInfo.getSymbol].showPrecision
        let value = data.value
        let fixNum = value.split('.')[1]

        if (value) {
          let operationVal = this._P.fixInput(value, paySshowPrecision)
          let values = Number(operationVal)
          let balance = Number(this.exchangeInterfaceInfo.balance)
          let availableAmount = values * this.exchangeInterfaceInfo.rate
          availableAmount = this._P.fixDUp(availableAmount, getSshowPrecision)
          values > balance && (this.errorInfo = this.Internationalization.overAvailableBalance, this.isCanFlash = false)
          this.comparisonSize(availableAmount)
          this.setObjKeyV() // 当手动输入值的时候取消套餐的选中
          if (fixNum && fixNum.length > paySshowPrecision) {
            this.$nextTick(() => {
              this.formList.payCoinNum.value = operationVal
            })
          }
        }
      }
    },
    closeDialog () {
      this.setExPw = false
      this.detailAlert = false
    },
    // 用来做 收到 币种数量 与 限额 做比较
    comparisonSize (availableAmount) {
      let minLimit = Number(this.exchangeInterfaceInfo.minQuantity)
      let maxLimit = Number(this.exchangeInterfaceInfo.maxQuantity)
      availableAmount < minLimit && (this.errorInfo = this.Internationalization.lessThanMiniLimit, this.isCanFlash = false)
      availableAmount > maxLimit && (this.errorInfo = this.Internationalization.moreThanMaxLimit, this.isCanFlash = false)
      this.myData.getQuantity = this._P.lastD(availableAmount)
      if (!this.zoologyUserInfoData.giveQuantity) { // 从未选择套餐兑换 的 时候， 赠送平台币
        for (let i = 0; i < this.exchangeInterfaceInfo.comboMap.length; i++) {
          // pc页面展示的时候 福利 左 ---》 右  由 大 --- 》 小
          if (Number(this.myData.getQuantity) >= Number(this.exchangeInterfaceInfo.comboMap[i].getQuantity)) {
            this.giveQuantity = '+' + this.exchangeInterfaceInfo.comboMap[i].giveQuantity
            break
          } else {
            this.giveQuantity = ''
          }
        }
      }
    },
    // 兑换界面信息
    exchangeInterface () {
      this.axios({
        url: this.$store.state.url.openPlatform.exchange_interface,
        header: {},
        method: 'POST',
        params: {
          paySymbol: this.formList.payCoin.value,
          exchangeSymbol: this.getZoologySymbol
        }
      }).then(res => {
        if (res.code.toString() === '0') {
          let data = res.data
          if (data) {
            this.exchangeInterfaceInfo.minQuantity = data.minQuantity
            this.exchangeInterfaceInfo.maxQuantity = data.maxQuantity
            this.exchangeInterfaceInfo.balance = data.balance
            if (this.coinList) {
              this.exchangeInterfaceInfo.balance = this._P.fixD(this.exchangeInterfaceInfo.balance, this.coinList[this.formList.payCoin.value].showPrecision)
              this.exchangeInterfaceInfo.balance = this._P.lastD(this.exchangeInterfaceInfo.balance)
            }
            this.exchangeInterfaceInfo.rate = data.rate
            this.exchangeInterfaceInfo.getSymbol = data.getSymbol
            this.exchangeInterfaceInfo.paySymbol = data.paySymbol
            this.exchangeInterfaceInfo.comboMap = data.comboMap
            this.exchangeInterfaceInfo.lockMapList = data.lockMapList
            this.exchangeInterfaceInfo.id = data.id
          } else {
            this.exchangeInterfaceInfo.minQuantity = 0
            this.exchangeInterfaceInfo.maxQuantity = 0
            this.exchangeInterfaceInfo.balance = 0
            this.exchangeInterfaceInfo.rate = 0
            this.exchangeInterfaceInfo.getSymbol = ''
            this.exchangeInterfaceInfo.paySymbol = ''
            this.exchangeInterfaceInfo.comboMap = []
            this.exchangeInterfaceInfo.lockMapList = []
            this.exchangeInterfaceInfo.id = ''
            this.$store.dispatch('setTipState', {text: this.Internationalization.rateErr, type: 'error'})
          }
        } else {
          this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
        }
      })
    },
    // 快速兑换
    fastFlash () {
      this.myData.paySymbol = this.exchangeInterfaceInfo.paySymbol
      this.myData.getSymbol = this.exchangeInterfaceInfo.getSymbol
      this.myData.payQuantity = this.formList.payCoinNum.value
      this.myData.rate = this.exchangeInterfaceInfo.rate
      this.myData.id = this.exchangeInterfaceInfo.id
      for (let item in this.myData) {
        if (this.myData[item] !== undefined && !this.myData[item] && item !== 'time' && item !== 'period' && item !== 'lockFee' && item !== 'quantity' && item !== 'lockEarnings') {
          this.$store.dispatch('setTipState', {text: this.Internationalization.pleaseCheck, type: 'error'})
          this.isCanFlash = false
          return false
        }
      }
      if (!this.isCanFlash) {
        this.$store.dispatch('setTipState', {text: this.Internationalization.pleaseCheck, type: 'error'})
        return false
      }
      if (!this.ifSetExchangePwd) {
        this.setExPw = true
      } else {
        this.passWordAlert = true  // 打开 输入 交易 密码 弹窗
      }
    },
    // 全部
    allEnter () {
      this.errorInfo = ''
      this.isCanFlash = true
      this.formList.payCoinNum.value = this.exchangeInterfaceInfo.balance
      let availableAmount = this.formList.payCoinNum.value * this.exchangeInterfaceInfo.rate
      availableAmount = this._P.fixD(availableAmount, this.coinList[this.exchangeInterfaceInfo.paySymbol].showPrecision)
      this.comparisonSize(availableAmount)
    },
    // 给每一条套餐数据 增加 布尔值
    setObjKeyV () {
      this.exchangeInterfaceInfo.comboMap.forEach(k => {
        this.$set(k, 'isChoose', false)
      })
    },
    // 选择福利
    chooseWelfare (item) {
      this.setObjKeyV()
      this.$set(item, 'isChoose', true)
      this.isCanFlash = true
      this.errorInfo = ''
      this.comparisonSize(item.getQuantity)
      let num = item.getQuantity / this.exchangeInterfaceInfo.rate
      this.formList.payCoinNum.value = num = this._P.fixD(num, this.coinList[this.exchangeInterfaceInfo.paySymbol].showPrecision)
      let balance = Number(this.exchangeInterfaceInfo.balance)
      this.formList.payCoinNum.value > balance && (this.errorInfo = this.Internationalization.overAvailableBalance, this.isCanFlash = false)
    },
    // 关闭输入 交易 密码弹窗
    closePassWordAlert () {
      this.passWordAlert = false
    },
    // 提交订单请求  输入完成 交易 密码 之后 触发 这个 函数
    submitRequest () {
      if (!this.secondClick) {
        return false
      }
      this.secondClick = false
      if (this.exchangeInterfaceInfolockMapListLeng) {
        // 锁仓收益
        this.myData.lockEarnings = this._P.accMul(this.myData.getQuantity, this.myData.lockFee)
        this.myData.lockEarnings = this._P.lastD(this._P.fixD(this.myData.lockEarnings, this.coinList[this.myData.getSymbol].showPrecision))
      }
      let { paySymbol, payQuantity, getSymbol, getQuantity, rate, id, lockFee, period, lockEarnings} = this.myData
      this.axios({
        url: this.$store.state.url.openPlatform.rapid_exchange,
        header: {},
        method: 'POST',
        params: { paySymbol, payQuantity, getSymbol, getQuantity, rate, id, lockFee, period, lockEarnings}
      }).then((res) => {
        if (res.code.toString() === '0') {
          this.$store.dispatch('setTipState', {text: this.Internationalization.flashSuc})
          this.getRecodeDetail(res.data.record.id)
          this.exchangeInterface()
          this.$emit('reGetRecordInfo')
        } else {
          this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
        }
        this.secondClick = true
      })
    },
    getRecodeDetail (id) {
      this.axios({
        url: this.$store.state.url.openPlatform.exchange_detail,
        header: {},
        method: 'POST',
        params: {
          id: id
        }
      }).then((res) => {
        if (res.code.toString() === '0') {
          let data = res.data.exchange
          this.detailAlertData.paySymbol = data.paySymbol
          this.detailAlertData.payQuantity = data.payQuantity
          this.detailAlertData.getSymbol = data.getSymbol
          this.detailAlertData.getQuantity = data.getQuantity
          this.detailAlertData.exchangeNumber = data.exchangeNumber
          this.detailAlertData.ctime = data.ctime
          this.detailAlertData.ctime = this._P.formatTime(this.detailAlertData.ctime)
          this.detailAlertData.rate = data.rate
          this.detailAlertData.lockFee = this.myData.lockFee
          this.detailAlertData.period = this.myData.period
          this.detailAlertData.lockEarnings = this.myData.lockEarnings
          this.detailAlert = true
        } else {
          this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
        }
      })
    },
    // 锁仓分红套餐选择
    chooseLockedPackage (item, index) {
      this.myData.lockFee = item.fee
      this.myData.period = item.period
      this.myData.time = item.time
      this.myData.quantity = item.quantity
      let lockedPackage = document.getElementById('lockedPackage')
      let aLockedItem = lockedPackage.getElementsByClassName('locked_item')
      let lockedItemArr = [...aLockedItem]
      lockedItemArr.forEach(i => {
        i.classList.remove('lockedSelected')
      })
      this.$refs['lockedPackage' + index][0].classList.add('lockedSelected')
    }
  }
}
</script>
